package com.cn.ccp.action.system;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;

import jxl.Sheet;
import jxl.Workbook;

import org.apache.log4j.Logger;

import com.cn.ccp.action.BaseAction;
import com.cn.ccp.bean.FacultyBean;
import com.cn.ccp.bean.FilePathBean;
import com.cn.ccp.bean.GradeBean;
import com.cn.ccp.bean.SpecialtyBean;
import com.cn.ccp.bean.UserBean;
import com.cn.ccp.util.CCPContants;


public class StudentAction extends BaseAction {
	private Logger log = Logger.getLogger(StudentAction.class);
	private UserBean userBean ;
	private List<UserBean> userList ;
	private List<String> specialtyList ;
	private SelectItem[] facultySelectItem ;
	private SelectItem[] specialtySelectItem ;
	private SelectItem[] gradeSelectItem ;
	
	private String facultyIDBack = "" ;
	
	//查询字段
	private String number ;
	private String searchUserType ;
	private String searchStatus ;
	private String searchUserName ;
	private String searchFacultyId ;
	private String searchSpecialtyId;
	
	
	public void initData(){
		number = "";
		searchStatus = "-1";
		searchUserName = "";
		searchFacultyId = "-1";
//		this.getpagedetail();
	}
	
	public void imageClick(){
		
	}
	
	public String doInportStudents(){
		log.info("--------doInportStudents()-----------");
//		if(userBean.getFacultyId().equals("-1")){
//			showMsg("faculty", "user_page_label_faculty_no_select");
//			return "";
//		}
//		if(userBean.getSpecialtyId().equals("-1")){
//			showMsg("specialty", "user_page_label_specialty_no_select");
//			return "";
//		}
//		if(userBean.getGrade() != null && userBean.getGrade().equals("-1")){
//			showMsg("grade", "user_page_label_grade_no_select");
//			return "";
//		}
		
		String savePath = CCPContants.SYS_PATH+"files"+File.separator + "students" + File.separator + CCPContants.getUserBean().getId() + File.separator;
		File[] f1 = new File(savePath).listFiles();
		if(f1 == null || f1.length <= 0){
			showMsg("uploadStudent", "user_page_label_upload_student_null_error");
			return "";
		}
		for(File f:f1)
			importFileForStudent(f);
		getpagedetail();
		return MAIN;
	}
	
	
	
	private void importFileForStudent(File file){
		Sheet sheet;
        Workbook book;
        try{
        	Map<String ,String> keyValueMap = new HashMap<String, String>(); 
        	book = Workbook.getWorkbook(file); 
        	sheet = book.getSheet(0);
        	//从第五行开始读取数据，前面四行预留
        	int allLines = sheet.getRows();
        	log.info("-----------------allLines = "+allLines);
        	for(int i=4;i<allLines;i++){
        		UserBean user = new UserBean();
        		user.setUserName(sheet.getCell(0, i).getContents());
        		user.setLogin_name(sheet.getCell(1, i).getContents());
        		user.setPassword(sheet.getCell(2, i).getContents());
        		user.setDormitoryAddress(sheet.getCell(3, i).getContents());
        		user.setEmail(sheet.getCell(4, i).getContents());
        		user.setSex(sheet.getCell(5, i).getContents());
        		user.setMobile(sheet.getCell(6, i).getContents());
        		user.setHomeAddress(sheet.getCell(7, i).getContents());
        		user.setBirtdate(sheet.getCell(8, i).getContents());
        		user.setZipCode(sheet.getCell(9, i).getContents());
        		user.setAdmissionTime(sheet.getCell(10, i).getContents());
        		String facultyName = sheet.getCell(11, i).getContents().trim();
        		if(keyValueMap.containsKey(facultyName)){
        			user.setFacultyId(keyValueMap.get(facultyName));
        		}else{
        			int facultyId = getFacultyService().getFacultyIdByfacultyName(facultyName.trim());
        			user.setFacultyId(""+facultyId);
        			keyValueMap.put(facultyName, ""+facultyId);
        		}
        		String specialtyName = sheet.getCell(12, i).getContents().trim();
        		if(keyValueMap.containsKey(specialtyName)){
        			user.setSpecialtyId(keyValueMap.get(specialtyName));
        		}else{
        			int specialtyId = getSpecialtyService().getSpecialtyIDBySpecialtyName(specialtyName.trim());
        			user.setSpecialtyId(""+specialtyId);
        			keyValueMap.put(specialtyName, ""+specialtyId);
        		}
        		String gradeName = sheet.getCell(13, i).getContents().trim();
        		if(keyValueMap.containsKey(gradeName)){
        			user.setGrade(keyValueMap.get(gradeName));
        		}else{
        			int gradeID = getGradeService().gradeIdByName(gradeName.trim());
        			user.setGrade(""+gradeID);
        			keyValueMap.put(gradeName, ""+gradeID);
        		}
        		
//        		user.setFacultyId(userBean.getFacultyId()) ;
//        		user.setSpecialtyId(userBean.getSpecialtyId());
//        		user.setGrade(userBean.getGrade());
        		
        		
        		user.setUserType("1");
        		getStudentService().sava(user);
        	}
        	
        }catch(Exception e){
        	log.error("read file failed : ",e);
        	file.delete();
        }
	}
	
	
	
	
	public String edit(){
		
		StringBuffer sb = new StringBuffer();
//		for(String s : specialtyList)
//			if(sb.length() == 0)
//				sb.append(s);
//			else
//				sb.append(":"+s);
//		userBean.setSpecialtyId(sb.toString());
		userBean.setUserType("1");
		if(userBean.getUserName().equals("")){
			showMsg("userName", "javax.faces.component.UIInput.REQUIRED");
			return "";
		}
		boolean checkStatus = getUserService().checkLoginUserNameIsOn(userBean.getId(), userBean.getLogin_name());
		if(checkStatus){
			showMsg("loginuserName", "user_page_label_login_username_error_1");
			return "";
		}
		
		if(userBean.getPassword().equals("")){
			showMsg("password", "javax.faces.component.UIInput.REQUIRED");
			return "";
		}
		boolean passwordISChange = false;
		if(userBean.getId() > 0 ){
			passwordISChange = getTeacherService().checkPasswrodIsChange(userBean.getId(), userBean.getPassword());
			if(passwordISChange){
				if(!userBean.getPassword().equals(userBean.getShowPassword())){
					showMsg("passwordok", "user_page_label_error_2");
					return "";
				}
			}
		}
		if(userBean.getDormitoryAddress().equals("")){
			showMsg("dormitoryAddress", "javax.faces.component.UIInput.REQUIRED");
			return "";
		}
		if(userBean.getEmail().equals("")){
			showMsg("email", "javax.faces.component.UIInput.REQUIRED");
			return "";
		}
		if(userBean.getMobile().equals("")){
			showMsg("mobile", "javax.faces.component.UIInput.REQUIRED");
			return "";
		}
		if(userBean.getHomeAddress().equals("")){
			showMsg("homeAddress", "javax.faces.component.UIInput.REQUIRED");
			return "";
		}
		if(userBean.getBirtdate().equals("")){
			showMsg("birtdate", "javax.faces.component.UIInput.REQUIRED");
			return "";
		}
		if(userBean.getAdmissionTime().equals("")){
			showMsg("admissionTime", "javax.faces.component.UIInput.REQUIRED");
			return "";
		}
		if(userBean.getZipCode().equals("")){
			showMsg("zipCode", "javax.faces.component.UIInput.REQUIRED");
			return "";
		}
		if(userBean.getFacultyId().equals("-1")){
			showMsg("faculty", "user_page_label_faculty_no_select");
			return "";
		}
		if(userBean.getSpecialtyId().equals("-1")){
			showMsg("specialty", "user_page_label_specialty_no_select");
			return "";
		}
		if(userBean.getGrade() != null && userBean.getGrade().equals("-1")){
			showMsg("grade", "user_page_label_grade_no_select");
			return "";
		}
//		if(userBean.getImage() == null || userBean.getImage().equals("")){
//			showMsg("image", "user_page_label_add_image_upload");
//			return "";
//		}
		
		if(userBean.getId() == 0)
			return save();
		else
			return update(passwordISChange);
	}
	
	public String editStudent(){
		userBean.setUserType("1");
		return edit();
	}
	
	public String editTeacher(){
		return edit();
	}
	
	public String save(){
		int userId = getStudentService().sava(userBean);
		FilePathBean filePathBean = getFilePathService().getFlagBean();
		String imgFile = filePathBean.getPath()+userBean.getImage();
		File file = new File(imgFile);
		String newPath = filePathBean.getPath()+userId+ File.separator + file.getName();
		File newDerect = new File(filePathBean.getPath()+userId+ File.separator);
		newDerect.mkdirs();
		try {
			new File(newPath).createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
		CCPContants.copyFile(imgFile, newPath);
		userBean.setId(userId);
		userBean.setImage(userId +"/" + file.getName());
		getStudentService().update(userBean ,false);
		file.delete(); 
		CCPContants.getFilePath(userBean.getImage() , getFilePathService(),filePathBean.getId() , userBean.getId());
		getpagedetail();
		return MAIN;
	}
	
	public String update(boolean passwordISChange){
		String imgFile = getFilePathService().getFlagBean().getPath()+userBean.getImage();
		File file = new File(imgFile);
		if(!file.exists()){
			UserBean tub = getUserService().findById(userBean.getId());
			userBean.setImage(tub.getImage());
		}
		boolean flag = getStudentService().update(userBean ,passwordISChange);
		if(flag){
			getpagedetail();
			return MAIN;
		}
		return "";
	}
	
	public void disableUser(){
		log.info("disable uses--------");
		for(UserBean u : userList){
			log.info(u);
			if(u.isDisable())
				getTeacherService().delete(u.getId());
		}
		selectAll = false;
		getpagedetail();
	}
	
	 private boolean selectAll; 
	 public String disAndselectAll() {  
		 	log.info("-----------------disAndselectAll()-------------------");
	        for (UserBean user : userList) {  
	        	if(user.getId() != 1){
	        		user.setDisable(selectAll);  
	        	}
	        	log.info(user);
	        } 
	        return "";
	    }  

		public boolean isSelectAll() {
			return selectAll;
		}

		public void setSelectAll(boolean selectAll) {
			this.selectAll = selectAll;
		}

	
	
	public void delete(){
		FacesContext context = FacesContext.getCurrentInstance();// 取得上下文
		String id = (String)context.getExternalContext().getRequestParameterMap().get("id");// 得到页面的参数
		log.info("----------delete()--------id = "+id);
		if(id == null || id.equals("null") || id.equals(""))
			return ;
		getStudentService().delete(Integer.parseInt(id));
		getpagedetail();
	}
	
	/**
	 * 进入批量导入页面
	 * @return
	 */
	public String goInport(){
		userBean = null ;;
		specialtyList = null ;
		facultySelectItem = null ;
		specialtySelectItem = null ;
		specialtyList = null ;
		gradeSelectItem = null;
		return "inportstudent";
	}
	
	
	public String goAdd(){
		userBean = null ;;
		specialtyList = null ;
		facultySelectItem = null ;
		specialtySelectItem = null ;
		specialtyList = null ;
		gradeSelectItem = null;
		
		return ADD;
	}
	
	public String showBean(){
		FacesContext context = FacesContext.getCurrentInstance();// 取得上下文
		String id = (String)context.getExternalContext().getRequestParameterMap().get("id");
		if(id == null || id.equals("null") || id.equals(""))
			return MAIN;
		userBean = (UserBean) getStudentService().findById(Integer.parseInt(id));
		
		if(userBean.getSpecialtyId() != null  && !userBean.getSpecialtyId().equals("")){
			String[] strs = userBean.getSpecialtyId().split(":");
			for (String s : strs) {
				if(specialtyList == null)
					specialtyList = new ArrayList<String>();
				if(!s.trim().equals(""))
					specialtyList.add(s.trim());
			}
		}
		
		if(userBean.getFacultyId() != null && !userBean.getFacultyId().equals("")){
			List<SpecialtyBean> splist = getSpecialtyService().getSpecialtyByFacultyId(Integer.parseInt(userBean.getFacultyId()));
			specialtySelectItem = new SelectItem[splist.size()];
			for (int i = 0; i < splist.size(); i++) 
				specialtySelectItem[i] = new SelectItem(""+splist.get(i).getId(),splist.get(i).getSpecialtyname());
		}
		
		if(userBean.getSpecialtyId() != null  && !userBean.getSpecialtyId().equals("")){
			List<GradeBean> list = getGradeService().geListGradeBySpecialty(userBean.getSpecialtyId().replaceFirst(":", ","));
			gradeSelectItem = new SelectItem[list.size()];
			for (int i = 0; i <list.size(); i++)
				gradeSelectItem[i] = new SelectItem(""+list.get(i).getId() , list.get(i).getGradeType());
		}
		String filePaht = CCPContants.getFilePath(userBean.getImage() , getFilePathService(),userBean.getFile_path_id() ,CCPContants.getUserBean().getId() );
		File file = new File(filePaht);
		userBean.setImage(CCPContants.getCurrUserId()+"/"+file.getName());
		return UPDATE ;
	}
	
	public void facultyChange(){
		log.info("---------facultyChange()-----------userBean.getFacultyId() = "+userBean.getFacultyId());
		specialtyList = new ArrayList<String>();
		gradeSelectItem = new SelectItem[0];
		List<SpecialtyBean> splist = getSpecialtyService().getSpecialtyByFacultyId(Integer.parseInt(userBean.getFacultyId()));
		log.info("---------facultyChange()-----------splist.size() = "+splist.size());
		specialtySelectItem = new SelectItem[splist.size()];
		for (int i = 0; i < splist.size(); i++) 
			specialtySelectItem[i] = new SelectItem(""+splist.get(i).getId(),splist.get(i).getSpecialtyname());
	}
	
	public void specialtyChange(){
		gradeSelectItem = null ;
		StringBuffer sb = new StringBuffer();
		for(String s :specialtyList)
			if(sb.length() == 0)
				sb.append(s);
			else
				sb.append(","+s);
//		if(sb.length() != 0){
			List<GradeBean> list = getGradeService().geListGradeBySpecialty(userBean.getSpecialtyId());
			gradeSelectItem = new SelectItem[list.size()];
			for (int i = 0; i < list.size(); i++) 
				gradeSelectItem[i] = new SelectItem(""+list.get(i).getId(),list.get(i).getGradeType());
//		}
	}
	
	public void search(){
		this.getpagedetail();
	}
	
	
	
	public void searchClear(){
		number = "";
		searchUserType = "-1" ;
		searchStatus = "-1" ;
		searchUserName = "" ;
		searchFacultyId = "-1" ;
		searchSpecialtyId = "-1";
		specialtySelectItem = null ;
		specialtyList = null ;
	}
	
	@Override
	public void getpagedetail() {
		setItemCount(getStudentService().getCount(number, searchUserType, searchStatus, searchUserName, searchFacultyId, searchSpecialtyId));
		int currentpage = getCurrentPage();
		int pagesize = getPageSize();
		int start = (currentpage - 1) * pagesize;
		if(start < 0)
			start = 0 ;
		userList = getStudentService().pageQuery(start, pagesize, number, searchUserType, searchStatus, searchUserName, searchFacultyId, searchSpecialtyId);
	}
	
	public UserBean getUserBean() {
		@SuppressWarnings("unchecked")
		Map<String, String> varMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		String fileName = varMap.get("fileName");
		String errorInfo = varMap.get("errorInfo");
		if(userBean == null){
			userBean = new UserBean();
		}
		if(fileName != null && !fileName.equals("")){
			userBean.setImage("files/"+CCPContants.getCurrUserId()+"/"+fileName);
		}
		if(errorInfo != null && !errorInfo.equals("")){
			showMsg("image", errorInfo);
			userBean.setImage("");
		}
		return userBean;
	}

	public void setUserBean(UserBean userBean) {
		this.userBean = userBean;
	}

	public List<UserBean> getUserList() {
		if(userList == null || userList.size() == 0)
			getpagedetail();
		return userList;
	}

	public void setUserList(List<UserBean> userList) {
		this.userList = userList;
	}

	public List<String> getSpecialtyList() {
		if(specialtyList == null)
			specialtyList = new ArrayList<String>();
		return specialtyList;
	}

	public void setSpecialtyList(List<String> specialtyList) {
		this.specialtyList = specialtyList;
	}

	public SelectItem[] getFacultySelectItem() {
		if(facultySelectItem == null){
			List<FacultyBean> list = getFacultyService().getAllFaculty();
			facultySelectItem = new SelectItem[list.size()];
			for (int i = 0; i < list.size(); i++) {
				facultySelectItem[i] = new SelectItem(""+list.get(i).getId() , list.get(i).getFacultyName());
			}
		}
		return facultySelectItem;
	}

	public void setFacultySelectItem(SelectItem[] facultySelectItem) {
		this.facultySelectItem = facultySelectItem;
	}

	public SelectItem[] getSpecialtySelectItem() {
		if(specialtySelectItem == null)
			specialtySelectItem = new SelectItem[0];
		return specialtySelectItem;
	}

	public void setSpecialtySelectItem(SelectItem[] specialtySelectItem) {
		this.specialtySelectItem = specialtySelectItem;
	}

	public String getFacultyIDBack() {
		return facultyIDBack;
	}

	public void setFacultyIDBack(String facultyIDBack) {
		this.facultyIDBack = facultyIDBack;
	}

	public String getSearchUserType() {
		return searchUserType;
	}

	public void setSearchUserType(String searchUserType) {
		this.searchUserType = searchUserType;
	}
	public String getSearchStatus() {
		return searchStatus;
	}

	public void setSearchStatus(String searchStatus) {
		this.searchStatus = searchStatus;
	}

	public String getNumber() {
		return number;
	}

	public void setNumber(String number) {
		this.number = number;
	}

	public String getSearchUserName() {
		return searchUserName;
	}

	public void setSearchUserName(String searchUserName) {
		this.searchUserName = searchUserName;
	}

	public String getSearchFacultyId() {
		return searchFacultyId;
	}

	public void setSearchFacultyId(String searchFacultyId) {
		this.searchFacultyId = searchFacultyId;
	}

	public String getSearchSpecialtyId() {
		return searchSpecialtyId;
	}

	public void setSearchSpecialtyId(String searchSpecialtyId) {
		this.searchSpecialtyId = searchSpecialtyId;
	}

	public SelectItem[] getGradeSelectItem() {
		if(gradeSelectItem == null)
			gradeSelectItem = new SelectItem[0];
		return gradeSelectItem;
	}

	public void setGradeSelectItem(SelectItem[] gradeSelectItem) {
		this.gradeSelectItem = gradeSelectItem;
	}

}
